<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="员工姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="queryDept">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="Emps" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="sn" label="编号" width="90" sortable>
			</el-table-column>
			<el-table-column prop="username" label="用户名" width="90"  sortable>
			</el-table-column>
      <el-table-column prop="age" label="年龄" width="90"  sortable>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="180"  sortable>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"  sortable>
      </el-table-column>
			<el-table-column prop="state" label="状态" width="120" sortable>
        <template scope="scope">
          <span v-if="scope.row.state=='1'" style="color: green">正常</span>
          <span v-if="scope.row.state=='0'" style="color: red">停用</span>
        </template>
			</el-table-column>
      <el-table-column prop="shop.name" label="店铺名" width="160" sortable>
			</el-table-column>
			<el-table-column prop="department.name" label="上级部门" min-width="160" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="page" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="员工名" prop="username">
					<el-input v-model="editForm.username" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="editForm.age" auto-complete="off"></el-input-number>
        </el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="0">禁用</el-radio>
						<el-radio class="radio" :label="1">启用</el-radio>
					</el-radio-group>
				</el-form-item>
        <!--
          :key="item.value"  表示唯一
          :label="item.label"  选中之后显示在框里面的值
          :value="item.value"  选中之后要返回给模型的值

          特别注意  这个可以 :value="item.id"   就不行  :value="item" 怎么在上面去加上一个value-key
          -->
				<!--<el-form-item label="">
          <el-select v-model="editForm.manager_id" placeholder="请选择">
            <el-option  v-for="item in employees" :key="item.id" :label="item.username" :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
				</el-form-item>-->
        <el-form-item label="上级部门">
          <!--<el-input v-model="editForm.parent_id" :min="0" :max="200"></el-input>-->
          <div class="block">
            <el-cascader
                v-model="editForm.department"
                :options="options"
                :props="{ checkStrictly: true,
                          value:'id',    //选中后返回的值
                          label:'name'   //显示的值
                        }"
                clearable></el-cascader>
          </div>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	export default {
		data() {
			return {
				filters: {
					keyword: ''
				},
        //装员工的数据
        employees:[],
        //树的部门
        options: [],
				Emps: [],
				total: 0,
        pageSize : 5,
				page: 1,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
        title:"",
				editLoading: false,
				editFormRules: {
          username:[
            { required: true, message: '请输入用户名', trigger: 'blur' }
          ],
          email:[
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
          ]
				},
				//编辑界面数据
				editForm: {
					id: 0,
          username: '',
          age: '',
          email: '',
          department:[],
					state: 0,
				}
			}
		},
		methods: {
			handleCurrentChange(val) {
				this.page = val;
				this.getEmps();
			},
      queryDept(){
			  this.page = 1
        this.getEmps();
      },
			//获取部门列表
			getEmps() {
				let para = {
          currentPage: this.page,
					keyword: this.filters.keyword,
          pageSize:this.pageSize
				};
				this.listLoading = true;//开启忙等
        this.$http.post("/emp/pagelist",para).then(res=>{
            this.total = res.data.total;
            this.Emps = res.data.data;
            this.listLoading = false;//关闭忙等
        })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '温馨提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;//开启忙等
					// let para = { id: row.id };//json数据
          this.$http.delete("/emp/"+row.id).then(res=>{
            this.listLoading = false;//关闭忙等
            if(res.data.success){//成功的情况
              this.$message({
                message: res.data.msg,
                type: 'success'
              });
            }else{//失败的情况
              this.$message({
                message: res.data.msg,
                type: 'error'
              });
            }
            //可以不设置   疑问  如果当前页数据被删除完成了怎么处理
            this.page = 1 //回到首页
            this.getEmps();//重新加载页面
          })
				}).catch(() => {
				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
			  //进入页面之前  重置表单验证
        if(this.$refs['editForm']){
          this.$refs['editForm'].resetFields();//重置表单验证
        }
			  // this.employeeQuery()

        //查询树
        this.TreeQuery()

				this.editFormVisible = true;//控制对话框是否显示 true 显示 false不显示
        this.title = "编辑"
        //为什么能回显数据
				this.editForm = Object.assign({}, row); //克隆  保证原始数据不会发生改变
        //点击编辑回显上级部门
        //将数据取出来变成数组
        if(row.department.id){
          // var dir =  row.department.dirPath.split("/")// /65/66/67   "" "65" "66" "67"
          var path = []//空数组
          // for (let i = 1; i < dir.length-1; i++) {
            //将字符串转为int类
            path.push(parseInt(row.department.id))
          // }
        }
        this.editForm.department=path //将数组赋值给department
			},
			//显示新增界面
			handleAdd: function () {
			  //重置表单验证
        if(this.$refs['editForm']){
          this.$refs['editForm'].resetFields();//重置表单验证
        }
			  //去查询员工数据
			  // this.employeeQuery()
        //查询树
        this.TreeQuery()

				this.editFormVisible = true;//控制对话框是否显示 true 显示 false不显示
        this.title = "新增"
        //初始化表单
				this.editForm = {
          sn:"",
          username: '',
          age: '',
          email: '',
          department:"",
          state: 0,
				};
			},
			//编辑
			editSubmit: function () {
			  //手动触发验证规则
				this.$refs.editForm.validate((valid) => {
				  //valid 判断你的验证是否通过  true  false
					if (valid) {
						this.$confirm('确认提交吗？', '温馨提示', {}).then(() => {
							this.editLoading = true;
							//封装为json了
							let para = Object.assign({}, this.editForm);//克隆数据
              if(para.department){//有值
                //将数组转为对象
                para.department_id = para.department[para.department.length - 1]
                para.department = null
              }
              this.$http.put("/emp",para).then(res=>{
                this.editLoading = false;
                if(res.data.success){//成功的情况
                  this.$message({
                    message: res.data.msg,
                    type: 'success'
                  });
                }else{//失败的情况
                  this.$message({
                    message: res.data.msg,
                    type: 'error'
                  });
                }
                //可以不设置   疑问  如果当前页数据被删除完成了怎么处理
                this.page = 1 //回到首页
                this.getEmps();//重新加载页面
              })
              this.editFormVisible = false;
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
			  //这里是数组
				var ids = this.sels.map(item => item.id);//获取到sels这里面的所有的id
				this.$confirm('确认删除选中记录吗？', '温馨提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;//开启忙等
          //发送请求
          this.$http.patch("/dept/department",ids).then(res=>{
            this.listLoading = false;//关闭忙等
            if(res.data.success){//成功的情况
              this.$message({
                message: res.data.msg,
                type: 'success'
              });
            }else{//失败的情况
              this.$message({
                message: res.data.msg,
                type: 'error'
              });
            }
            this.page = 1
            this.getEmps();
          })
				}).catch(() => {
				});
			},
      //用来查询所有的员工数据
      employeeQuery:function (){
        this.$http.get("/emp/employee").then(res=>{
          this.employees = res.data
        })
      },
      TreeQuery:function(){
        this.$http.get("/dept/tree").then(res=>{

          this.options = res.data
        })
      }

		},
		mounted() {
			this.getEmps();
		}
	}
</script>


<style scoped>
</style>